package com.springcloudalibaba.gateway.configurer;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import com.springcloudalibaba.bclass.base.BaseResult;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description: TODO SpringCloudGateway基于Sentinel进行限流是通过Filter实现的。需要向容器中注入SentinelGatewayFilter过滤器和SentinelGatewayBlockExceptionHandler异常回调
 * @Author: lixing
 * @Date: 2020/11/21 15:40
 */
//@Configuration
public class RequestRateLimiterForGatewaySentinelRouteConfig {
    private final List<ViewResolver> viewResolverList;
    private final ServerCodecConfigurer serverCodecConfigurer;

    public RequestRateLimiterForGatewaySentinelRouteConfig(ObjectProvider<List<ViewResolver>> viewResolverListProvider, ServerCodecConfigurer serverCodecConfigurer) {
        this.viewResolverList = viewResolverListProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    // 初始化 SentinelGatewayFilter 过滤器
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }

    // 初始化 SentinelGatewayBlockExceptionHandler 限流异常处理器
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        return new SentinelGatewayBlockExceptionHandler(viewResolverList, serverCodecConfigurer);
    }

    // 自定义限流异常页面
    @PostConstruct
    public void initBlockHandlers() {
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                return ServerResponse.status(HttpStatus.OK).
                        contentType(MediaType.APPLICATION_JSON).
                        body(BodyInserters.fromValue(new BaseResult<String>().fail("触发流控")));
            }
        };
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }

    // 配置初始化限流参数
    @PostConstruct
    public void initGatewayRules() {
        Set<GatewayFlowRule> gatewayFlowRuleSet = new HashSet<>();
        // 添加 BFF-API-AUTH-ROUTE路由 限流规则
        gatewayFlowRuleSet.add(
                new GatewayFlowRule("BFF-API-AUTH-ROUTE") // 路由ID
                        .setCount(1) // 限流阈值
                        .setIntervalSec(1)); // 统计时间窗口，默认单位秒
        // 添加 BFF-API-ADMIN-ROUTE路由 限流规则
        gatewayFlowRuleSet.add(
                new GatewayFlowRule("BFF-API-ADMIN-ROUTE") // 路由ID
                        .setCount(1) // 限流阈值
                        .setIntervalSec(1)); // 统计时间窗口，默认单位秒
        GatewayRuleManager.loadRules(gatewayFlowRuleSet);
    }

}
